package com.example.administrator.xxnapp.fragment.tucao;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.xxnapp.R;
import com.example.administrator.xxnapp.bean.CommentListBean;
import com.example.administrator.xxnapp.bean.TuCaoBean;
import com.example.administrator.xxnapp.bean.UserBean;
import com.example.administrator.xxnapp.tucao.SendTuCaoActivity;
import com.example.administrator.xxnapp.util.Config;
import com.gyf.barlibrary.BarHide;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.mdruby.baselibrary.BaseFragment;
import cn.mdruby.baselibrary.utils.ABAppUtil;
import cn.mdruby.baselibrary.utils.AndroidBug5497Workaround;
import cn.mdruby.baselibrary.utils.KeySoftUtil;
import cn.mdruby.baselibrary.utils.ObjectStoreUtil;

/**
 */
public class TuCaoFragment extends BaseFragment implements IViewTuCao,OnRefreshListener,OnLoadmoreListener{
    @BindView(R.id.frag_tucao_RV)
    RecyclerView mRV;
    @BindView(R.id.frag_tucao_RefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.frag_tucao_LLayout_Bottom)
    LinearLayout mLLayoutBottom;
    @BindView(R.id.frag_tucao_ET_Comment)
    EditText mETComment;
    @BindView(R.id.frag_tucao_TV_Send)
    TextView mTVSend;
    @BindView(R.id.frag_tucao_RL_List)
    View mViewList;
    @BindView(R.id.empty_list_data_layout_TV_Title)
    TextView mTVEmptyTitle;
    @BindView(R.id.empty_list_data_layout_Root)
    View mViewBlankRoot;

    protected ImmersionBar mImmersionBar;
    private TuCaoPresenter mPresenter;
    private List<TuCaoBean> mDatas;
    private RVTuCaoAdapter mAdapter;
    private static TuCaoFragment fragment;
    private int pageCount = 1;
    private int groupPosition = -1;
    private int childPosition = -1;
    private int commentType = 0;
    private UserBean mUser;
    private boolean isError;

    public static TuCaoFragment getInstance(){
        if (fragment == null){
            synchronized (TuCaoFragment.class){
                if (fragment == null){
                    fragment = new TuCaoFragment();
                }
            }
        }
        return fragment;
    }

    @Override
    public int getLayoutId() {
        mImmersionBar = ImmersionBar.with(this);
       /* mImmersionBar
                .fitsSystemWindows(true)
                .statusBarColor(R.color.base_color)
                .init();*/
        return R.layout.fragment_tu_cao;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mImmersionBar != null){
         /*   mImmersionBar
                    .fitsSystemWindows(true)
                    .statusBarColor(R.color.base_color)
                    .init();*/
            mImmersionBar = ImmersionBar.with(getActivity());
            if (ABAppUtil.checkDeviceHasNavigationBar(getActivity())){
                mImmersionBar.navigationBarColor(R.color.white);
            }else {
                mImmersionBar.navigationBarEnable(false);
                mImmersionBar.hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR);
            }
            mImmersionBar.fitsSystemWindows(true)
                    .statusBarColor(R.color.base_color)
                    .init();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void initBeforeDatas() {
        mUser = (UserBean) ObjectStoreUtil.getObject(mContext,Config.Key.USER_OBJECT_KEY);
        mPresenter = new TuCaoPresenter(this,new TuCaoBean());
        mDatas = new ArrayList<>();
    }

    @Override
    public void setListeners() {
        mRV.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new RVTuCaoAdapter(mContext,mDatas);
        mRV.setAdapter(mAdapter);


        mRV.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
               removeEditText();
                return false;
            }
        });

        setAdapterListener();

        mRefreshLayout.setOnLoadmoreListener(this);
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableAutoLoadmore(false);

        page = 1;
        pageSize = 10;
        refreshTime = 200;
        mPresenter.getTuCao(page,pageSize,mUser.getUserId());
    }

    private void setAdapterListener() {
        mAdapter.setOnTuCaoItemClickListener(new RVTuCaoAdapter.OnTuCaoItemClickListener() {
            @Override
            public void praiseClick(int position) {
                //点赞
                TuCaoBean tuCaoBean = mDatas.get(position);
                int praise = tuCaoBean.getPraise() == 1?0:1;
                mPresenter.praise(tuCaoBean.getUserId(),tuCaoBean.getId(),praise,position);
            }

            @Override
            public void commentClick(int position) {
                //评论
                mLLayoutBottom.setVisibility(View.VISIBLE);
                KeySoftUtil.showSoftInput(mETComment);
                groupPosition = position;
                commentType = CommentListBean.CommnetTypeEnum.commentNoraml;
            }

            @Override
            public void onItemUserClick(int groupPosition,int childPosition, int userId) {
            }

            @Override
            public void onItemClick(int groupPosition,int childPosition, int commentType) {
                TuCaoFragment.this.groupPosition = groupPosition;
                if (mDatas.get(groupPosition).getCommentList().get(childPosition).getCommentUserId()!=mUser.getUserId()){
                    TuCaoFragment.this.commentType = CommentListBean.CommnetTypeEnum.reply;
                    mLLayoutBottom.setVisibility(View.VISIBLE);
                    KeySoftUtil.showSoftInput(mETComment);
                    String commentUserName = mDatas.get(groupPosition).getCommentList().get(childPosition).getCommentUserName();
                    mETComment.setHint("回复:"+commentUserName);
                }
            }
        });
    }


    @Override

    public void initViews(View view) {
        ButterKnife.bind(this,view);
        mImmersionBar = ImmersionBar.with(getActivity());
        if (ABAppUtil.checkDeviceHasNavigationBar(getActivity())){
            mImmersionBar.navigationBarColor(R.color.white);
        }else {
            mImmersionBar.navigationBarEnable(false);
            mImmersionBar.hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR);
        }
        mImmersionBar.fitsSystemWindows(true)
                .statusBarColor(R.color.base_color)
                .init();
//        mRV.getItemAnimator().setChangeDuration(0);
//        ((SimpleItemAnimator)mRV.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    @Override
    public void onResume() {
        super.onResume();
        AndroidBug5497Workaround.assistActivity(getActivity());
    }

    @Override
    public void getTuCaoSuccess(List<TuCaoBean> tuCaoBeans) {
        mRefreshLayout.setVisibility(View.VISIBLE);
        if (pageCount == 1){
            mDatas.clear();
        }
        if (mRefreshLayout.isLoading()){
            mRefreshLayout.finishLoadmore(refreshTime);
        }else if (mRefreshLayout.isRefreshing()){
            mRefreshLayout.finishRefresh(refreshTime);
        }

        mDatas.addAll(tuCaoBeans);
        isError = false;

        mRefreshLayout.setEnableLoadmore(true);
        mRefreshLayout.setEnableRefresh(true);
        mRV.setVisibility(mDatas.size()>0?View.VISIBLE:View.GONE);
        if (mDatas.size()>0){
            mAdapter.notifyDataSetChanged();
        }else {
            mTVEmptyTitle.setText("暂无数据");
        }
        mRefreshLayout.setEnableLoadmore(mDatas.size()>0);

    }

    @Override
    public void getTuCaoFinish() {
        if (mRefreshLayout.isRefreshing()){
            mRefreshLayout.finishRefresh(200);
        }else if (mRefreshLayout.isLoading()){
            mRefreshLayout.finishLoadmore(200);
        }
    }

    @Override
    public void getTuCaoError() {
        if (mDatas.size() == 0){
            mRefreshLayout.setVisibility(View.GONE);
            mRefreshLayout.setEnableLoadmore(false);
            mRefreshLayout.setEnableRefresh(false);
            mRV.setVisibility(View.GONE);
            isError = true;
            mTVEmptyTitle.setText("加载失败，请点击空白处重试");

            mViewBlankRoot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mPresenter.getTuCao(page,pageSize,mUser.getUserId());
                }
            });
        }
    }

    private void removeEditText(){
        if (KeySoftUtil.isSoftShowing(getActivity())){
            KeySoftUtil.hideSoftInput(mETComment);
            mETComment.setText("");
            mETComment.setHint("");
            mETComment.clearFocus();
            mLLayoutBottom.setVisibility(View.GONE);
        }
    }

    @OnClick(R.id.empty_list_data_layout_Root)
    public void onReLoad(View view){
        if (isError){
            mRefreshLayout.autoRefresh();
        }
    }

    @Override
    public void getPraiseSuccess(int position) {
        TuCaoBean tuCaoBean = mDatas.get(position);
        tuCaoBean.setPraise(tuCaoBean.getPraise() == 1?0:1);
        mAdapter.notifyItemChanged(position);
    }

    @Override
    public void postCommentSuccess(CommentListBean bean,int groupPosition) {
        TuCaoBean tuCaoBean = mDatas.get(groupPosition);
        tuCaoBean.getCommentList().add(bean);
        mAdapter.notifyDataSetChanged();
        removeEditText();
    }

    @OnClick(R.id.frag_tucao_IV_Edit)
    public void editTuCao(View view){
        Intent intent = new Intent(mContext,SendTuCaoActivity.class);
        startActivityForResult(intent, Config.RequestCode.INTO_TUCAO_EDIT);
    }

    @OnClick(R.id.frag_tucao_TV_Send)
    public void send(View view){
        if (!TextUtils.isEmpty(mETComment.getText().toString())){
            TuCaoBean tuCaoBean = mDatas.get(groupPosition);
            int atUserId = 0;
            switch (commentType){
                case CommentListBean.CommnetTypeEnum.commentNoraml:
                    atUserId = 0;
                    break;
                case CommentListBean.CommnetTypeEnum.reply:
                    atUserId = tuCaoBean.getUserId();
                    break;
            }
            mPresenter.upComment(tuCaoBean,mETComment.getText().toString(),mUser.getUserId(),atUserId,groupPosition);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == getActivity().RESULT_OK){
            switch (requestCode){
                case Config.RequestCode.INTO_TUCAO_EDIT:
                    pageCount = 1;
                    mPresenter.getTuCao(1,page*pageSize,mUser.getUserId());
                    break;
            }
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        pageCount = 1;
        mPresenter.getTuCao(1,page*pageSize,mUser.getUserId());
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page+=1;
        pageCount = page;
        mPresenter.getTuCao(page,pageSize,mUser.getUserId());
    }
}
